import React, {Component} from 'react';
import '../App.css';

import ReactTable from "../../node_modules/react-table";
import '../../node_modules/react-table/react-table.css'
import JSONPretty from '../../node_modules/react-json-pretty';

import {Card, Button, message} from 'antd'

/**
 * MemoryLeak
 */
class MemoryLeak extends Component {

    constructor() {
        super();
        this.leakInfos = [];
        this.state = {
            dataList: [],
            isRefreshing: true
        };
        this.setRefreshStatus = this.setRefreshStatus.bind(this);
    }

    refresh(leakInfo) {
        let hasLeakBefore = false;
        for (let i = 0; i < this.leakInfos.length; i++) {
            if (leakInfo && leakInfo.referenceKey && leakInfo.referenceKey === this.leakInfos[i].referenceKey) {
                this.leakInfos[i] = leakInfo;
                hasLeakBefore = true;
            }
        }
        if (!hasLeakBefore) {
            this.leakInfos.push(leakInfo);
            message.error("Memory leak.(发生内存泄漏)")
        }
        if (this.state.isRefreshing) {
            this.setState({dataList: this.leakInfos});
        }
    }

    setRefreshStatus() {
        this.setState((prevState) => ({
            isRefreshing: !prevState.isRefreshing,
            dataList: this.leakInfos
        }));
    }

    render() {
        let dataList = this.state.dataList;
        return (
            <Card title="Memory Leak(内存泄漏)" extra={<Button
                onClick={this.setRefreshStatus}>{this.state.isRefreshing ? "Stop" : "Start"}</Button>}>
                <ReactTable
                    sortable={true}
                    resizable={true}
                    filterable={true}
                    data={dataList}
                    columns={[
                        {
                            Header: "referenceKey",
                            accessor: "referenceKey"
                        }, {
                            Header: "leakTime",
                            accessor: "leakTime"
                        }, {
                            Header: "leakObjectName",
                            accessor: "leakObjectName"
                        }, {
                            Header: "statusSummary",
                            accessor: "statusSummary"
                        }
                    ]}
                    SubComponent={row => {
                        return (
                            <div style={{padding: "20px"}}>
                                <JSONPretty id="json-pretty" json={row.original.pathToGcRoot}/>
                            </div>
                        );
                    }}
                    defaultPageSize={8}
                    className="-striped -highlight"/>
            </Card>
        );
    }
}

export default MemoryLeak;
